package com.lfg.leetcode.leetcode0;


import com.alibaba.fastjson.JSONArray;

public class No59generateMatrix {

    public static void main(String[] args) {
        int[][] array = generateMatrix(3);
        System.out.println(JSONArray.toJSONString(array));
    }

    public static int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];
        int index = 0;

        int index1 = 0;
        int index2 = n - 1;
        int index3 = n - 1;
        int index4 = 0;

        int total = n * n;
        for (int i = 1; i <= total && index <= n / 2 + 1; ) {
            for (int j = index; j < n - index && i <= total; j++) {
                ret[index1][j] = i++;
            }
            for (int j = index + 1; j < n - index - 1 && i <= total; j++) {
                ret[j][index2] = i++;
            }
            for (int j = n - index - 1; j >= index && i <= total; j--) {
                ret[index3][j] = i++;
            }
            for (int j = n - index - 2; j > index && i <= total; j--) {
                ret[j][index4] = i++;
            }
            index++;
            index1++;
            index2--;
            index3--;
            index4++;
        }
        return ret;
    }
}

